package main

import (
	"chapter-01-hello/service"
	"context"
	"flag"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"time"
)

const (
	defaultName = "world"
)

var (
	addr = flag.String("addr", "127.0.0.1:9090", "the address to connect to")
	name = flag.String("name", defaultName, "Name to greet")
)

func main() {
	flag.Parse()
	// 连接到server端，此处禁用安全传输
	dial, err := grpc.NewClient(*addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer dial.Close()
	client := service.NewActionClient(dial)

	// 执行RPC调用并打印收到的响应数据
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	defer cancel()
	r, err := client.SayHello(ctx, &service.HelloRequest{Id: "1"})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Greeting: %s %s", r.GetName(), r.GetAge())
}

//func main() {
//	//获取当前目录
//	dir, err := os.Getwd()
//	if err != nil {
//		grpclog.Fatalf("Failed to get current directory: %v", err)
//	}
//	creds, err := credentials.NewClientTLSFromFile(path.Join(dir, "/key/server.pem"), "ximu.info")
//	if err != nil {
//		grpclog.Fatalf("Failed to create TLS credentials %v", err)
//	}
//	dial, err := grpc.Dial("127.0.0.1:9090", grpc.WithTransportCredentials(creds))
//	if err != nil {
//		panic(err)
//	}
//	defer func(dial *grpc.ClientConn) {
//		err := dial.Close()
//		if err != nil {
//			panic(err)
//		}
//	}(dial)
//	client := service.NewActionClient(dial)
//	hello, err := client.SayHello(context.Background(), &service.HelloRequest{Id: "1"})
//	if err != nil {
//		panic(err)
//	}
//	marshal, _ := json.Marshal(hello)
//	log.Println(string(marshal))
//}
